# pragma pack(push,1)
# typedef struct
# {
#     uint8_t     node_id;           // 节点id
#     uint32_t    satellite_time;   //精度50ms
#     uint32_t    packet_seq;        // 导航包计数
#     uint8_t     nav_state;         // 导航状态
#     int32_t     lon;               // 经纬度，1e-7deg
#     int32_t     lat;
#     int32_t     alt;               // 高度单位mm
#     int32_t     roll_rate;         // 角速度单位1e-4deg/s
#     int32_t     pitch_rate;
#     int32_t     yaw_rate;
#     int32_t     roll;              // 角度单位1e-4deg
#     int32_t     pitch;
#     int32_t     yaw;
#     int16_t     v_east;            // cm/s，1e-2m/s
#     int16_t     v_north;
#     int16_t     v_up;
#     int16_t     velocity;
#     int32_t     acc_x;             // 1e-4m/s2
#     int32_t     acc_y;
#     int32_t     acc_z;
#     uint8_t     selfcheck_status;  // 自检、对准标志
# //    uint16_t    laser_range;         // 激光测距，单位：0.1m
# //    int32_t     gimbal_pitch_0;          // 俯仰框架角，单位：0.01°
# //    int32_t     gimbal_yaw0;            // 偏航框架角，单位：0.01°
#     uint8_t     status_feedback1;     // 状态信息反馈1
#     uint8_t     status_feedback2;     // 状态信息反馈2
#     uint8_t     zoom_rate;      // 变焦倍数低8位，单位：0.1倍
#     uint8_t     status_feedback3;     // 状态反馈信息3
#     int16_t     target_offsetX;       // 目标脱靶量 X轴偏移角度，单位：0.05°
#     int16_t     target_offsetY;       // 目标脱靶量 Y轴偏移角度，单位：0.05°
#     int16_t     gimbal_roll;      // 横滚框架角，单位：0.01°
#     int16_t     gimbal_pitch;     // 俯仰框架角，单位：0.01°
#     int16_t     gimbal_yaw;   // 方位框架角，单位：0.01°
#     int16_t     att_roll;   // 横滚姿态角，单位：0.01°
#     int16_t     att_pitch;  // 俯仰姿态角，单位：0.01°
#     int16_t     att_rollrate;      // 横滚角速度，单位：0.01°/s
#     int16_t     att_pitchrate;     // 俯仰角速度，单位：0.01°/s
#     int16_t     att_yawrate;   // 方位角速度，单位：0.01°/s
#     uint16_t     laser_range;         // 激光测距，单位：0.1m
#     uint8_t     self_check_result;     // 自检结果
# } px4_to_agx_packet_t;
# #pragma pack(pop)


import pandas as pd
import re
import translate


def open_file(file_path):
    try:
        df = pd.read_csv(file_path)
        return df
    except FileNotFoundError:
        print("文件未找到。")
    except Exception as e:
        print("发生错误:", e)


def line_process(line, num_cols, start_byte_index=6, flag="mavlink"):
    index_cell = line.iloc[0]
    pattern = re.compile(r"\d+")
    index_match = re.match(pattern, index_cell)

    # 去除头部
    if index_match is not None:
        index = int(index_match.group(0))
        if index < start_byte_index:
            return

    data_type = get_type(line.iloc[2])
    name = get_name(line.iloc[1])

    if flag == "mavlink":
        unit = get_unit(line.iloc[3])
        description = get_descrip(line.iloc[4])
        print("\t", "<field type=\"", data_type, "\" name=\"", name, "\" units=\"", unit, "\">", description, "</field>")
    elif flag == "driver":
        print("\t", data_type, "\t", name, ";\t// ", end=' ')
        discrip = get_descrip_zh(line.iloc[4])
        # if type(discrip)==str:
        print(discrip, ", 单位: ", line.iloc[3])


def get_descrip(cell):
    if cell is None or isinstance(cell, float):
        return cell

    if '\n' in cell:
        lines = cell.split('\n')
        ans = ''
        # 打印每一行文本
        for line in lines:
            # 如果是冒号分隔, 第二部分是中文描述
            if ':' in line:
                parts = line.split(':')
                descrip = translate.trans(parts[1])
                ans += parts[0] + ':' + descrip + ', '
            elif '：' in line:
                parts = line.split('：')
                descrip = translate.trans(parts[1])
                ans += parts[0] + ':' + descrip + ', '
            else:
                descrip = translate.trans(line)
                ans += descrip + ', '
        return ans

    else:
        descrip = translate.trans(cell)
        return descrip


def get_descrip_zh(cell):
    if cell is None or isinstance(cell, float):
        return cell

    if '\n' in cell:
        lines = cell.replace('\n', ' ')
        return lines
    else:
        return cell


def get_unit(cell):
    # TODO lhl 240607 具体实现看情况
    return cell


def get_name(cell):
    name_en = translate.trans(cell)
    name = name_en.replace(" ", "_")
    return name.lower()


def get_type(cell):
    if cell in ["CHAR", "char", "UINT8"]:
        return "uint8_t"

    else:
        pattern = re.compile(r"([A-Za-z]+)(\d+)")
        match = re.findall(pattern, cell)
        if match:
            return match[0][0].lower() + match[0][1] + "_t"

        else:
            print(" Data type beyond consideration!")
            print("Data type is", cell)


def print_mav_msg_head():
    print("<message id=\"XX\" name=\"XXXXXXXXXXXXXX\">")
    print("\t<description>XXXXXXXXXXXXXXXXX</description>")


def print_drive_msg_end():
    print("</message>")


def print_mavlink():
    file_name = "protocol_definition.csv"
    df = open_file(file_name)

    # 获取表格的行数和列数
    num_rows, num_columns = df.shape

    print_mav_msg_head()
    # 逐行访问
    for row in range(1, num_rows):
        line = df.iloc[row]
        line_process(line, num_columns)

    print_drive_msg_end()

def print_driver():
    file_name = "protocol_definition.csv"
    df = open_file(file_name)

    # 获取表格的行数和列数
    num_rows, num_columns = df.shape

    print("#pragma pack(push,1)")
    print("typedef struct{")

    # 逐行访问
    for row in range(1, num_rows):
        line = df.iloc[row]
        line_process(line, num_columns, start_byte_index=6, flag="driver")

    print("}YOUR_PACKAGE_NAME_t;")
    print("#pragma pack(pop)")


if __name__ == "__main__":
    print_driver()
